package controllers

import (
	"encoding/json"
	"fmt"
	"snow-im/app/http/entities"
	"snow-im/app/models/ordermodel"
	"snow-im/app/services"
	"snow-im/app/utils"

	"github.com/gin-gonic/gin"
)

func GoodsList(c *gin.Context) {
	HandRes(c, services.GetGoods(), nil)
}

func AppCheck(c *gin.Context) {
	HandRes(c, map[string]interface{}{
		"is_audit": 0,
	}, nil)
}

func CreateOrder(c *gin.Context) {
	var req entities.OrderReq
	GenRequest(c, &req, func() {
		err := services.VerifyRecip(req.Uuid, req.Recipe)
		HandRes(c, nil, err)
	})
}

func OrderList(c *gin.Context) {
	var req entities.PageReq
	GenRequest(c, &req, func() {
		count, data := services.GetPageOrders(req.Page, req.PageSize, req.Uuid)
		HandRes(c, entities.PageRsp{Total: count, Datas: data}, nil)
	})
}

func OrderNotify(c *gin.Context) {
	defer func() {
		err := recover()
		fmt.Print(err)
	}()
	body, err := ReadBody(c)
	if err != nil {
		utils.Log(c, "notify", err)
	}
	utils.Log(c, "notify", string(body))
	var req map[string]interface{}
	err = json.Unmarshal(body, &req)
	var rtype = req["notification_type"].(string)
	var oriId = req["original_transaction_id"].(string)
	var recipes = req["unified_receipt"].(map[string]interface{})["latest_receipt_info"].([]interface{})
	var order = ""
	if len(recipes) > 0 {
		order = recipes[0].(map[string]interface{})["transaction_id"].(string)
	}
	if rtype == "INITIAL_BUY" || rtype == "DID_RENEW" || rtype == "INTERACTIVE_RENEWAL" || rtype == "DID_RECOVER" {
		_, err := ordermodel.GetInstance().GetDb().Where("trans_id = ? and origin_id = ?", order, oriId).Update(ordermodel.Order{Status: 1})
		fmt.Println(err)
	} else if rtype == "CANCEL" {
		ordermodel.GetInstance().GetDb().Where("trans_id = ? and origin_id = ?", order, oriId).Update(ordermodel.Order{Status: 2})
	}
}
